<?php
	########################################################
	# Mantis Bugtracker Add-On
	#
	#                     Time Tracker
	#
	# by Elmar Schumacher (elmar.schumacher@web.de)
	# GAMBIT Consulting GmbH
	########################################################

	$bug_id = gpc_get_int( 'bug_id' );
	$table = config_get("timetracking_table");
	
# Time record POST
	if( isset($_GET['time_value']) ){
	
		# Current UserID
		$user = auth_get_current_user_id();
		$time_info = db_prepare_string($_GET["time_info"]);
		
		# Work on Time-Entry so we can eval it
		$time_value = $_GET["time_value"];
		$time_value = strtr( $time_value, ",", ".");
		$time_value = doubleval($time_value);
		
		$time_unit = $_GET["time_unit"];
		
		# Trigger in case of non-evaluable entry
		if ( $time_value == 0 ) {
			trigger_error( lang_get( 'time_value_error' ), ERROR );
		}
		
		# Converting mandays into hours for unified database values
		if($_GET["time_unit"] == "md"){
			$time_value = $time_value * config_get('consultant_manday_definition');
		}
		
		# For record-keeping we also calc the costs according to the hourly charges 
		$costs = $time_value * config_get('consultant_hourly_charge');
		
		# Write Post-Data to DB
		if( db_connect( config_get('hostname'), config_get('username'), config_get('password'), config_get('database_name') )){
			$now = date("Y-m-d G:i:s");
			$year = $_GET["year"];
			$month = $_GET["month"];
			$day = $_GET["day"];
			
			$query = "INSERT INTO $table
				    		( user, bugid, expenditure_date, hours, costs, time_unit, timestamp, info )
				  		VALUES
				    		( '$user', '$bug_id', '$year-$month-$day', '$time_value', '$costs', '$time_unit', '$now', '$time_info')";
			if(!db_query($query)){
				trigger_error( ERROR_DB_QUERY_FAILED, ERROR );
			}
			
			# Event is logged in the project
			history_log_event_direct( $bug_id, lang_get( 'time_tracking' ), "$day.$month.$year: $costs Euro", "set", $user );
		} else {
			trigger_error( ERROR_DB_CONNECT_FAILED, ERROR );
		}
	}

# DELETE Entry: A time record needs to be deleted
	if( isset($_GET['delete_id']) ){
		$delete_id = $_GET['delete_id'];
		if ( access_has_bug_level( config_get( 'timetracking_delete_threshold' ), $bug_id ) ) {
			if( db_connect( config_get('hostname'), config_get('username'), config_get('password'), config_get('database_name') )){			
				$query_delete = "DELETE FROM $table WHERE id = $delete_id";
				db_query($query_delete);
			} else {
				trigger_error( ERROR_DB_CONNECT_FAILED, ERROR );
			}
		}
	}

# Pull all Time-Record entries for the current Bug
	if( db_connect( config_get('hostname'), config_get('username'), config_get('password'), config_get('database_name') )){
		$query_pull_timerecords = "SELECT * FROM $table WHERE bugid = $bug_id ORDER BY timestamp DESC";
		$result_pull_timerecords = db_query($query_pull_timerecords);
		$num_timerecords = db_num_rows( $result_pull_timerecords );
	} else {
		trigger_error( ERROR_DB_CONNECT_FAILED, ERROR );
	}
	
# Get Sum for this bug
	if( db_connect( config_get('hostname'), config_get('username'), config_get('password'), config_get('database_name') )){
		$table = config_get("timetracking_table");
		$query_pull_costs_hours = "SELECT SUM(costs) as costs, SUM(hours) as hours FROM $table WHERE bugid = $bug_id";
		$result_pull_costs_hours = db_query($query_pull_costs_hours);
		$row_pull_costs_hours = db_fetch_array( $result_pull_costs_hours );		
	} else {
		trigger_error( ERROR_DB_CONNECT_FAILED, ERROR );
	}
?>
<br>

  <table class="width100" cellspacing="1">
    <tr>
      <td colspan="7" class="row-category"><div align="left"><a name="timerecord"></a><?php echo lang_get( 'time_tracking' ); ?></div>
      </td>
    </tr>
    <tr class="row-category">
      <td><div align="center"><?php echo lang_get( 'time_user' ); ?></div>
      </td>
      <td><div align="center"><?php echo lang_get( 'time_expenditure_date' ); ?></div>
      </td>
      <td><div align="center"><?php echo lang_get( 'time_hours' ); ?>/<?php echo lang_get( 'time_mandays' ); ?></div>
      </td>
      <td><div align="center"><?php echo lang_get( 'time_information' ); ?></div>
      </td>
      <td><div align="center"><?php echo lang_get( 'time_costs_auto' ); ?></div>
      </td>
      <td><div align="center"><?php echo lang_get( 'time_entry_date' ); ?></div>
      </td>
      <td>&nbsp;</td>
    </tr>
	
	<?php if ( access_has_bug_level( config_get( 'timetracking_add_threshold' ), $bug_id ) ) { ?>
	
	<form name="time_tracking" method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>#timerecord">

	<? # Nesessary Parameter. Due to base inconsistency we have a double entry ?>
	<input type="hidden" name="bug_id" value="<?php echo $bug_id;  ?>">
	<input type="hidden" name="id" value="<?php echo $bug_id;  ?>">
	
    <tr <?php echo helper_alternate_class() ?>>
      <td><? echo user_get_name( auth_get_current_user_id() ) ?></td>
      <td nowrap><div align="center">
        <?php 
			$current_date = explode ("-", date("Y-m-d"));
		?>
          <select tabindex="5" name="day">
            <?php print_day_option_list( $current_date[1] ) ?>
          </select>
          <select tabindex="6" name="month">
            <?php print_month_option_list( $current_date[1] ) ?>
          </select>
          <select tabindex="7" name="year">
            <?php print_year_option_list( $current_date[0] ) ?>
          </select>
        </div>
      </td>
      <td><table width="100%" border="0" cellspacing="1">
          <tr>
            <td><div align="right">
                <select name="time_unit">
                  <option value="hr" selected><?php echo lang_get( 'time_hours' ) ?></option>
                  <option value="md"><?php echo lang_get( 'time_mandays' ) ?></option>
                </select>
              </div>
            </td>
            <td><div align="left">
                <input name="time_value" type="text">
              </div>
            </td>
          </tr>
        </table>
      </td>
      <td><div align="center">
          <input type="text" name="time_info">
        </div>
      </td>
      <td>&nbsp;</td>
      <td>
      </td>
      <td><input name="<?php echo lang_get( 'time_submit' ) ?>" type="submit" value="<?php echo lang_get( 'time_submit' ) ?>">
      </td>
    </tr>
	</form>
	<? } # END Access Control ?>
    <?php
		for ( $i=0; $i < $num_timerecords; $i++ ) {
			$row = db_fetch_array( $result_pull_timerecords );
	?>
    <tr <?php echo helper_alternate_class() ?>>
      <td><? echo user_get_name($row["user"]); ?></td>
      <td><div align="center"><?php echo date("d.m.Y", strtotime($row["expenditure_date"])); ?> </div>
      </td>
	  <? 
	  	$mdBold = "";
		$mdBoldStop = "";
		$hrBold = "";
		$hrBoldStop = "";
			
		if($row["time_unit"]=="md"){
			$mdBold = "<b>";
			$mdBoldStop = "</b>";
			$hrBold = "";
			$hrBoldStop = "";
		} else {
			$mdBold = "";
			$mdBoldStop = "";
			$hrBold = "<b>";
			$hrBoldStop = "</b>";
		}
	  
	  ?>
      <td><div align="right"><?php echo $hrBold.number_format($row["hours"], 2, ',', '.').$hrBoldStop; ?> / <?php echo $mdBold.number_format($row["hours"]/config_get('consultant_manday_definition'), 2, ',', '.').$mdBoldStop; ?></div>
      </td>
      <td><?php echo $row["info"]; ?> </td>
      <td><div align="right"><?php echo number_format($row["costs"], 2, ',', '.'); ?> &euro;</div>
      </td>
      <td><div align="center"><?php echo date("d.m.Y G:i:s", strtotime($row["timestamp"])); ?> </div>
      </td>
      <td>
	<?php # DELETE Button just available for 'Delete-Bug Users'
			if ( access_has_bug_level( config_get( 'timetracking_delete_threshold' ), $bug_id ) ) {?>
			<a href="<?php echo $_SERVER['PHP_SELF']; ?>?bug_id=<?php echo $bug_id; ?>&id=<?php echo $bug_id; ?>&delete_id=<?php echo $row["id"]; ?>#timerecord"><?php echo lang_get( 'time_tracking_delete' ) ?></a></td>
	<?php } ?>
	</tr>
    <?php } ?>
	<tr class="row-category">
      <td><?php echo lang_get( 'time_sum' ) ?></td>
      <td>&nbsp;</td>
      <td><div align="center"><b><?php echo number_format($row_pull_costs_hours['hours'], 2, ',', '.'); ?> / <?php echo number_format($row_pull_costs_hours['hours']/config_get('consultant_manday_definition'), 2, ',', '.'); ?></b></div></td>
      <td>&nbsp;</td>
      <td><div align="center"><b><?php echo number_format($row_pull_costs_hours['costs'], 2, ',', '.'); ?> &euro;</b></div></td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  </table>
